import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import CourseRecordListABI from "../contract/ABIs/CourseList.json"; // 课程记录列表合约 ABI
import UserABI from '../contract/ABIs/User.json'; // 管理员合约 ABI

import CourseRecordListAddress from "../contract/ADDRESSes/CourseListAddress.js" // 课程记录列表合约地址
import UserNavBar from './nav/UserNavBar.js';
// import '../static/indexcss/aacsss.css';
import Eye from './Eye.js'

const Student_Info = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractCourseRecordList, setcontractCourseRecordList] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [contractUser, setcontractUser] = useState(false);
    const [StudentInfo, setStudentInfo] = useState(null);

    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建课程记录合约实例
                    const courseRecordListInstance = new web3Instance.eth.Contract(
                        CourseRecordListABI,
                        CourseRecordListAddress
                    );
                    setcontractCourseRecordList(courseRecordListInstance);

                    // 创建管理员合约实例
                    const userInstance = new web3Instance.eth.Contract(
                        UserABI,
                        address
                    );
                    setcontractUser(userInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await userInstance.methods.getUserAddr().call();
                    console.log("currentAddress:", currentAddress, "ownerAddress:", ownerAddress);
                    // 检查当前账户是否是管理员本人
                    setIsAdmin(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);




    const getStudentInfo = async () => {
        if (contractCourseRecordList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress, "Input:");

                // 调用智能合约的某个函数
                await contractCourseRecordList.methods.getStudentInfo().call({ from: fromAddress }).then((res) => {
                    if (!res || (typeof res === 'object' && Object.keys(res).length === 0) || (typeof res !== 'object' && res === 0)) {
                        throw new Error('查询结果为空或为0');
                    }

                    // alert("查询成功")
                    console.log("res:", res);
                    setStudentInfo(res);
                })

            } catch (error) {
                console.error(error);
                alert("查询失败")
            }
        }
    };


    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}


            {/* 管理员界面 */}
            {/* {isAdmin && ( */}
            <div>

                {/* <nav className="navbar navbar-expand-lg fixed-top portfolio-navbar gradient navbar-dark">
                        <div className="container">
                            <a className="navbar-brand logo" href="#">先锋积分</a>
                            <button className="navbar-toggler" data-bs-target="#navbarNav" data-bs-toggle="collapse">
                                <span className="visually-hidden">Toggle navigation</span>
                                <span className="navbar-toggler-icon" />
                            </button>
                            <div className="collapse navbar-collapse" id="navbarNav">
                                <ul className="navbar-nav ms-auto">
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}`}>用户首页</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_GetOwnInfo`}>用户查询个人信息</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_updateOwnerInfo`}>修改个人信息</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_JoinActivity`}>参加活动</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_uploadMaterial`}>上传材料</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_ReacherPoint`}>查询积分</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_MaterialList`}>用户上传材料列表</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/Student_Info`}>查询用户学生信息</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_registerStudent`}>学生注册</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/`}>退出登录</Link>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav> */}
                <UserNavBar address={address} />
                <main className="page hire-me-page">
                    <section className="portfolio-block hire-me">

                        <div className="foreground-component">
                            <Eye />
                            <div className="container">
                                <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                    data-bs-theme="light"
                                    style={{
                                        backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                    }}
                                >

                                    <div class="mb-3">
                                        <h1>查询个人学生信息</h1>
                                        {StudentInfo && Object.keys(StudentInfo).length > 0 ? (
                                            <table style={{ borderCollapse: 'collapse', margin: '1em 0', width: '100%' }}>
                                                <thead>
                                                    <tr>
                                                        <th style={{ backgroundColor: '#f2f2f2', borderBottom: '1px solid #ddd', color: 'black', padding: '8px', textAlign: 'center' }}>真实姓名：{StudentInfo[0]}</th>
                                                        <th style={{ backgroundColor: '#f2f2f2', borderBottom: '1px solid #ddd', color: 'black', padding: '8px', textAlign: 'center' }}>身份证号码：{StudentInfo[1]}</th>
                                                        <th style={{ backgroundColor: '#f2f2f2', borderBottom: '1px solid #ddd', color: 'black', padding: '8px', textAlign: 'center' }}>学号：{StudentInfo[2]}</th>
                                                        <th style={{ backgroundColor: '#f2f2f2', borderBottom: '1px solid #ddd', color: 'black', padding: '8px', textAlign: 'center' }}>班级：{StudentInfo[3]}</th>
                                                        <th style={{ backgroundColor: '#f2f2f2', borderBottom: '1px solid #ddd', color: 'black', padding: '8px', textAlign: 'center' }}>学历：{StudentInfo[4].toString()}</th>
                                                        <th style={{ backgroundColor: '#f2f2f2', borderBottom: '1px solid #ddd', color: 'black', padding: '8px', textAlign: 'center' }}>年级：{StudentInfo[5].toString()}</th>

                                                    </tr>
                                                </thead>
                                            </table>
                                        ) : (
                                            <p> No userInfo information available.</p>
                                        )}


                                        <div className="mb-3 mt-4">
                                            <button className="btn btn-primary btn-lg d-block w-100" onClick={getStudentInfo}>查询</button>
                                        </div>



                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </main>
            </div>
            {/* )} */}
        </div>
    );
}

export default Student_Info;